package com.cmz.controller;

import com.cmz.common.api.dto.StandardResponse;
import com.cmz.common.dto.Response;
import com.cmz.common.utils.TokenUtil;
import com.cmz.dto.LoginDto;
import com.cmz.entity.OnlyAloneUser;
import com.cmz.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/login")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(value = "登录")
public class LoginController {

    private final UserService userService;

    @PostMapping
    @ApiOperation(value = "/login", notes = "登录信息")
    public StandardResponse<String> checkUser(@RequestBody LoginDto loginDto) throws Exception {
        String userName = loginDto.getUserName();
        String password = loginDto.getPassword();
        if(StringUtils.isBlank(userName)
        || StringUtils.isBlank(password)){
            throw new Exception("用户名或者密码为空");
        }
        List<OnlyAloneUser> userList = userService.queryTotalList(userName);
        for (int i = 0; i < userList.size(); i++) {
            OnlyAloneUser user = userList.get(i);
            if(userName.equals(user.getUserName()) && password.equals(user.getPassword()) ) {
                LoginDto loginDtos = new LoginDto();
                loginDtos.setUserName(user.getUserName());
                //添加token
                SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String datetime = tempDate.format(new Date(System.currentTimeMillis()));
                String token = TokenUtil.sign(user.getUserName(), datetime);
//                //断言token不为空，并以用户名作为key，存入redis
//                assert token != null;
//                redisTemplate.opsForValue().set(loginVo.getUserName(),token);
//                return R.ok(loginVo);
                return Response.newInstance(token);
            }
        }
        return Response.newErrorInstance("登录失败","登录失败");
    }
}
